<template>
  <div class="dashboard-container">
    <div class="app-container">
      <UploadExcel :on-success="onSuccess" />
    </div>
  </div>
</template>

<script>
import { importExcel } from '@/api/user'
import Employees from '@/api/constant/employees'
export default {
  methods: {

    // 导入
    async onSuccess(data) {
      // console.log(data)
      // console.log(data.results)
      // (改造数据)遍历转换 对象 键名
      const newData = data.results.map(user => {
        return this.ZhToEn(user)
      })
      console.log(newData)

      // 发送请求
      await importExcel(newData)

      this.$message.success('导入成功')

      // 跳转到上一页
      this.$router.back()
    },
    // 遍历转换 对象 键名
    ZhToEn(user) {
      const newUser = {}
      const dict = {
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      for (const key in user) {
        const enKey = dict[key]
        let value = user[key]

        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          // 时间格式的转换(调用方法)
          newUser[enKey] = (typeof value) === 'string' ? new Date(value) : new Date(this.formatExcelTime(value))
        } else if (enKey === 'formOfEmployment') {
          const obj = Employees.hireType.find(item => item.value === value)
          // console.log(obj)
          value = obj ? obj.id : '未知'
          newUser[enKey] = value
        } else if (enKey === 'mobile') {
          newUser[enKey] = String(value)
        } else {
          newUser[enKey] = value
        }
      }
      // console.log(newUser)
      return newUser
    },

    // 时间格式的转换
    formatExcelTime(num, format = '-') {
      num = Number(num)	// 强制类型转化，以防传来的值是字符串
      let millisecond = 0	// 转化后的毫秒数
      if (num > 60) {
        millisecond = (num - 25569) * 60 * 60 * 24 * 1000
      } else {
        millisecond = (num - 25568) * 60 * 60 * 24 * 1000
      }
      const date = new Date(millisecond)	// 根据转化后的毫秒数获取对应的时间
      const yy = date.getFullYear()
      const mm = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      const dd = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      return yy + format + mm + format + dd	// 返回格式化后的日期
    }
  }
}
</script>

<style>

</style>
